﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Aribaccio;
using Aribaccio.Datum;
using Microsoft.EntityFrameworkCore;

namespace BDPAutodetect.DataService
{
    /// <summary>
    /// 数据库连接操作基本服务类
    /// </summary>
    public class DataServiceBase : IDataServiceBase
    {
        /// <summary>
        /// 数据库连接操作上下文实例
        /// </summary>
        protected CoreDBContext ContextService { get; set; }
        /// <summary>
        /// 数据库连接操作上下文-工厂接口实例
        /// </summary>
        protected ICoreDBContextFactory ContextFactory { get; set; }
        /// <summary>
        /// 带参构造函数
        /// </summary>
        /// <param name="argCoreDBContextFactory">数据库连接操作上下文-工厂接口实例对象</param>
        public DataServiceBase(ICoreDBContextFactory argCoreDBContextFactory)
        {
            this.ContextFactory = argCoreDBContextFactory;
            this.ContextService = (CoreDBContext)this.ContextFactory.CreateCoreDbContext();
        }

        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <returns>返回处理结果</returns>
        public Result Insert<T>(T argItem) where T : class { return this.ChangesSave(DBOperateType.Insert, argItem); }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns></returns>
        public Result Insert<T>(List<T> argItems) where T : class { return this.ChangesSave(DBOperateType.Insert, argItems.ToArray()); }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <returns>返回异步处理结果</returns>
        public async Task<Result> InsertTask<T>(T argItem) where T : class { return await this.ChangesSaveTask(DBOperateType.Insert, argItem); }
        /// <summary>
        /// 插入数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns>返回异步处理结果</returns>
        public async Task<Result> InsertTask<T>(List<T> argItems) where T : class { return await this.ChangesSaveTask(DBOperateType.Insert, argItems.ToArray()); }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <returns>返回处理结果</returns>
        public Result Update<T>(T argItem) where T : class { return this.ChangesSave(DBOperateType.Update, argItem); }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns>返回处理结果</returns>
        public Result Update<T>(List<T> argItems) where T : class { return this.ChangesSave(DBOperateType.Update, argItems.ToArray()); }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <returns>返回异步处理结果</returns>
        public async Task<Result> UpdateTask<T>(T argItem) where T : class { return await this.ChangesSaveTask(DBOperateType.Update, argItem); }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns>返回异步处理结果</returns>
        public async Task<Result> UpdateTask<T>(List<T> argItems) where T : class { return await this.ChangesSaveTask(DBOperateType.Update, argItems.ToArray()); }
        /// <summary>
        /// 更新数据[批量Lambda]
        /// </summary>
        /// <param name="argItem">要修改实体中 修改后的属性 </param>
        /// <param name="argWhereLambda">查询实体的条件</param>
        /// <param name="argProNames">Lambda的形式表示要修改的实体属性名</param>
        /// <returns></returns>
        public Result UpdateWhere<T>(T argItem, Expression<Func<T, bool>> argWhereLambda, params string[] argProNames) where T : class
        {
            //获取条件数据
            List<T> ListModifes = this.ContextService.Set<T>().Where(argWhereLambda).ToList();
            //修改更新数据，并返回集合数据
            ListModifes = this.UpdateModelListToList(argItem, ListModifes, argProNames);
            //保存更新数据
            return this.ChangesSave(DBOperateType.Update, ListModifes.ToArray());
        }
        /// <summary>
        /// 更新数据[批量非Lambda]
        /// </summary>
        /// <param name="argItem">要修改实体中 修改后的属性 </param>
        /// <param name="argWhereLambda">查询实体的条件</param>
        /// <param name="argProNames">Lambda的形式表示要修改的实体属性名</param>
        /// <returns></returns>
        public async Task<Result> UpdateWhereTask<T>(T argItem, Expression<Func<T, bool>> argWhereLambda, params string[] argProNames) where T : class
        {
            //获取条件数据
            List<T> ListModifes = await this.ContextService.Set<T>().Where(argWhereLambda).ToListAsync();
            //修改更新数据，并返回集合数据
            ListModifes = this.UpdateModelListToList(argItem, ListModifes, argProNames);
            //异步保存更新数据
            return await this.ChangesSaveTask(DBOperateType.Update, ListModifes.ToArray());
        }
        /// <summary>
        /// 获取更新数据后的结果集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="argItem"></param>
        /// <param name="argItems"></param>
        /// <param name="argProNames"></param>
        /// <returns></returns>
        private List<T> UpdateModelListToList<T>(T argItem, List<T> argItems, params string[] argProNames) where T : class
        {
            List<T> ResultItems = argItems;
            try
            {
                Type t = typeof(T);
                List<PropertyInfo> proInfos = t.GetProperties(BindingFlags.Instance | BindingFlags.Public).ToList();
                Dictionary<string, PropertyInfo> dicPros = new Dictionary<string, PropertyInfo>();
                proInfos.ForEach(p =>
                {
                    if (argProNames != null && argProNames.Length > 0)
                    {
                        if (argProNames.Contains(p.Name)) { dicPros.Add(p.Name, p); }
                    }
                    else { dicPros.Add(p.Name, p); }
                });
                foreach (var item in dicPros)
                {
                    PropertyInfo proInfo = item.Value;// dicPros[proName];
                    object? newValue = proInfo.GetValue(argItem, null);
                    foreach (T m in ResultItems) { proInfo.SetValue(m, newValue, null); }
                }
            }
            catch (Exception) { ResultItems = argItems; }
            return ResultItems;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <param name="argSlaveType">主从数据库类型</param>
        /// <returns>返回处理结果</returns>
        public Result Delete<T>(T argItem) where T : class { return this.ChangesSave(DBOperateType.Delete, argItem); }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns>返回处理结果</returns>
        public Result Delete<T>(List<T> argItems) where T : class { return this.ChangesSave(DBOperateType.Delete, argItems.ToArray()); }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItem">对象模型实体</param>
        /// <param name="argSlaveType">主从数据库类型</param>
        /// <returns>返回处理结果</returns>
        public async Task<Result> DeleteTask<T>(T argItem) where T : class { return await this.ChangesSaveTask(DBOperateType.Delete, argItem); }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argItems">对象模型实体集合</param>
        /// <returns>返回处理结果</returns>
        public async Task<Result> DeleteTask<T>(List<T> argItems) where T : class { return await this.ChangesSaveTask(DBOperateType.Delete, argItems.ToArray()); }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argDelWhere">匿名函数查询条件</param>
        /// <returns></returns>
        public Result DeleteWhere<T>(Expression<Func<T, bool>> argDelWhere) where T : class
        {
            List<T> listDels = this.ContextService.Set<T>().Where(argDelWhere).ToList();
            return this.ChangesSave(DBOperateType.Delete, listDels.ToArray());
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argDelWhere">匿名函数查询条件</param>
        /// <returns></returns>
        public async Task<Result> DeleteWhereTask<T>(Expression<Func<T, bool>> argDelWhere) where T : class
        {
            List<T> listDels = await this.ContextService.Set<T>().Where(argDelWhere).ToListAsync();
            return await this.ChangesSaveTask(DBOperateType.Delete, listDels.ToArray());
        }

        /// <summary>
        /// 数据保存[只能批量增或删或改]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argDBOperateType">数据库操作类型</param>
        /// <param name="argItems">对象模型实体或实体集合</param>
        /// <returns>返回处理结果</returns>
        public Result ChangesSave<T>(DBOperateType argDBOperateType, params T[] argItems) where T : class
        {
            Result ResultData = new Result();
            try
            {
                switch (argDBOperateType)
                {
                    case DBOperateType.Insert:
                        this.ContextService.Set<T>().AddRange(argItems);
                        break;
                    case DBOperateType.Update:
                        this.ContextService.Set<T>().UpdateRange(argItems);
                        break;
                    case DBOperateType.Delete:
                        this.ContextService.Set<T>().RemoveRange(argItems);
                        break;
                }
                int iResultChange = this.ContextService.SaveChanges();
                if (iResultChange <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行失败!!";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = $"[数据保存][" + argDBOperateType.ToStringName() + $"]->异常：{(ep.InnerException != null ? ep.InnerException.Message : ep.Message)}";
            }
            return ResultData;
        }
        /// <summary>
        /// 执行增加,删除,修改操作(或调用存储过程)
        /// </summary>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public Result ChangesExecuteSQL(string argSQLText, params DbParameter[] argCommandParms)
        {
            Result ResultData = new Result();
            try
            {
                int nResult = this.ContextService.Database.ExecuteSqlRaw(argSQLText, argCommandParms);
                if (nResult <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL操作失败！";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = $"[执行SQL操作]->异常：{(ep.InnerException != null ? ep.InnerException.Message : ep.Message)}";
            }
            return ResultData;
        }
        /// <summary>
        /// 数据保存异步[只能批量增或删或改]
        /// </summary>
        /// <returns></returns>
        public async Task<Result> ChangesSaveTask<T>(DBOperateType argDBOperateType, params T[] argItems) where T : class
        {
            Result ResultData = new Result();
            try
            {
                switch (argDBOperateType)
                {
                    case DBOperateType.Insert:
                        await this.ContextService.Set<T>().AddRangeAsync(argItems);
                        break;
                    case DBOperateType.Update:
                        this.ContextService.Set<T>().UpdateRange(argItems);
                        break;
                    case DBOperateType.Delete:
                        this.ContextService.Set<T>().RemoveRange(argItems);
                        break;
                }
                int nResult = await this.ContextService.SaveChangesAsync();
                //等待结果
                if (nResult <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行失败!!";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = $"[异步数据保存][" + argDBOperateType.ToStringName() + $"]->异常：{(ep.InnerException != null ? ep.InnerException.Message : ep.Message)}";
            }
            return ResultData;
        }
        /// <summary>
        /// 执行增加,删除,修改操作(或调用存储过程)
        /// </summary>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public async Task<Result> ChangesExecuteSQLTask(string argSQLText, params DbParameter[] argCommandParms)
        {
            Result ResultData = new Result();
            try
            {
                int nResult = await this.ContextService.Database.ExecuteSqlRawAsync(argSQLText, argCommandParms);
                if (nResult <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL操作失败！";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = $"[执行SQL操作]->异常：{(ep.InnerException != null ? ep.InnerException.Message : ep.Message)}";
            }
            return ResultData;
        }

        /// <summary>
        /// 查询是否存在[根据唯一编码]
        /// </summary>
        /// <param name="argUniqueCode">唯一编码</param>
        /// <returns></returns>
        public Result Exsits<T>(object argUniqueCode) where T : class
        {
            Result ResultData = new Result() { ResultCode = ResultStatus.Failure };
            try
            {
                T? Item = this.ContextService.Set<T>().Find(argUniqueCode);
                if (Item != null) { ResultData.ResultCode = ResultStatus.Succeed; }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询是否存在[根据查询条件Lambda]
        /// </summary>
        /// <param name="argUniqueCode">唯一编码</param>
        /// <returns></returns>
        public Result Exsits<T>(Expression<Func<T, bool>> argWhereLambda) where T : class
        {
            Result ResultData = new Result() { ResultCode = ResultStatus.Failure };
            try
            {
                bool bResult = this.ContextService.Set<T>().Any(argWhereLambda);
                if (bResult) { ResultData.ResultCode = ResultStatus.Succeed; }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }

        /// <summary>
        /// 查询数据[根据唯一编码]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argUniqueCode">唯一编码</param>
        /// <returns></returns>
        public ResultModel<T> SelectUnique<T>(object argUniqueCode) where T : class
        {
            ResultModel<T> ResultData = new ResultModel<T>();
            try
            {
                //查询方法
                ResultData.Data = this.ContextService.Set<T>().Find(argUniqueCode);
                //返回处理数据
                if (ResultData.Data == null)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询]
        /// </summary>
        /// <param name="argWhereLambda">查询条件(lambda表达式的形式生成表达式目录树)</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public ResultModel<T> SelectModelItem<T>(Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultModel<T> ResultData = new ResultModel<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = this.ContextService.Set<T>().Where(argWhereLambda).AsNoTracking().FirstOrDefault();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = this.ContextService.Set<T>().Where(argWhereLambda).FirstOrDefault();
                        break;
                }
                //返回处理数据
                if (ResultData.Data == null)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[全部数据]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns>实体对象集合</returns>
        public IQueryable<T> SelectQueryable<T>(ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            switch (argTrackStatus)
            {
                default:
                case ExecuteStatus.No://查询时，去除状态跟踪 AsNoTracking
                    return this.ContextService.Set<T>().AsNoTracking();
                case ExecuteStatus.Yes:
                    return this.ContextService.Set<T>();
            }
        }
        /// <summary>
        /// 查询数据[根据条件查询]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argWhereLambda">查询条件(lambda表达式的形式生成表达式目录树)</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns>实体对象集合</returns>
        public IQueryable<T> SelectQueryable<T>(Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            switch (argTrackStatus)
            {
                default:
                case ExecuteStatus.No://查询时，去除状态跟踪 AsNoTracking
                    return this.ContextService.Set<T>().Where(argWhereLambda).AsNoTracking();
                case ExecuteStatus.Yes:
                    return this.ContextService.Set<T>().Where(argWhereLambda);
            }
        }
        /// <summary>
        /// 查询数据[全部数据]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns>实体对象集合信息</returns>
        public ResultList<T> SelectModelItems<T>(ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = this.ContextService.Set<T>().AsNoTracking().ToList();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = this.ContextService.Set<T>().ToList();
                        break;
                }
                //返回处理数据
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询]
        /// </summary>
        /// <param name="argWhereLambda">查询条件(lambda表达式的形式生成表达式目录树)</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public ResultList<T> SelectModelItems<T>(Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = this.ContextService.Set<T>().Where(argWhereLambda).AsNoTracking().ToList();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = this.ContextService.Set<T>().Where(argWhereLambda).ToList();
                        break;
                }
                //返回处理数据
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询和名称排序]
        /// </summary>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argSortName">排序名称</param>
        /// <param name="argSortDirection">asc 或 desc</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是跟踪的</param>
        /// <returns></returns>
        public ResultList<T> SelectModelItems<T>(Expression<Func<T, bool>> argWhereLambda, string argSortName, string argSortDirection, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                //获取查询数据
                IQueryable<T> QueryData = this.SelectQueryable(argWhereLambda, argTrackStatus);
                //判断检查，查询数据
                if (QueryData != null && QueryData.Count() > 0)
                {
                    //调用自定义扩展方法
                    QueryData = QueryData.DataSorting(argSortName, argSortDirection);
                    ResultData.Data = QueryData.ToList();
                }
                else
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询和Lambda排序]
        /// </summary>
        /// <typeparam name="Tkey">排序字段类型</typeparam>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argOrderLambda">排序条件</param>
        /// <param name="argSortStatus">排序状态【Yes升序,No降序/倒序】</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public ResultList<T> SelectModelItems<T, Tkey>(Expression<Func<T, bool>> argWhereLambda, Expression<Func<T, Tkey>> argOrderLambda, ExecuteStatus argSortStatus = ExecuteStatus.Yes, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                //获取查询数据
                IQueryable<T> QueryData = this.SelectQueryable(argWhereLambda, argTrackStatus);
                //判断检查，查询数据
                if (QueryData != null && QueryData.Count() > 0)
                {
                    //查询后，再排序
                    switch (argSortStatus)
                    {
                        case ExecuteStatus.Yes:
                            QueryData = QueryData.OrderBy(argOrderLambda);
                            break;
                        case ExecuteStatus.No:
                            QueryData = QueryData.OrderByDescending(argOrderLambda);
                            break;
                    }
                    ResultData.Data = QueryData.ToList();
                }
                else
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询分页数据[根据条件查询和Lambda排序]
        /// </summary>
        /// <typeparam name="Tkey">排序字段类型</typeparam>
        /// <param name="argPageIndex">页码</param>
        /// <param name="argPageSize">页容量/每页数量</param>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argOrderLambda">排序条件</param>
        /// <param name="argSortStatus">排序状态【Yes升序,No降序/倒序】</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public ResultListPage<T> SelectModelItemsPager<T, Tkey>(int argPageIndex, int argPageSize, Expression<Func<T, bool>> argWhereLambda, Expression<Func<T, Tkey>> argOrderLambda, ExecuteStatus argSortStatus = ExecuteStatus.Yes, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultListPage<T> ResultData = new ResultListPage<T>() { PageIndex = argPageIndex, PageSize = argPageSize };
            try
            {
                //获取查询数据
                IQueryable<T> QueryData = this.SelectQueryable(argWhereLambda, argTrackStatus);
                //判断检查，查询数据
                if (QueryData != null && QueryData.Count() > 0)
                {
                    ResultData.RecordCount = QueryData.Count();
                    //查询后，再排序
                    switch (argSortStatus)
                    {
                        case ExecuteStatus.Yes:
                            QueryData = QueryData.OrderBy(argOrderLambda);
                            break;
                        case ExecuteStatus.No:
                            QueryData = QueryData.OrderByDescending(argOrderLambda);
                            break;
                    }
                    //排序后，再分页
                    QueryData = QueryData.Skip((argPageIndex - 1) * argPageSize).Take(argPageSize);
                    //设置返回数据
                    ResultData.Data = QueryData.ToList();
                }
                else
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询分页数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询分页数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }

        /// <summary>
        /// 查询数据[根据唯一编码]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argUniqueCode">唯一编码</param>
        /// <returns></returns>
        public async Task<ResultModel<T>> SelectUniqueTask<T>(object argUniqueCode) where T : class
        {
            ResultModel<T> ResultData = new ResultModel<T>();
            try
            {
                //查询方法
                ResultData.Data = await this.ContextService.Set<T>().FindAsync(argUniqueCode);
                //返回处理数据
                if (ResultData.Data == null)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询]
        /// </summary>
        /// <param name="argWhereLambda">查询条件(lambda表达式的形式生成表达式目录树)</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public async Task<ResultModel<T>> SelectModelItemTask<T>(Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultModel<T> ResultData = new ResultModel<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = await this.ContextService.Set<T>().Where(argWhereLambda).AsNoTracking().FirstOrDefaultAsync();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = await this.ContextService.Set<T>().Where(argWhereLambda).FirstOrDefaultAsync();
                        break;
                }
                //返回处理数据
                if (ResultData.Data == null)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[全部数据]
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns>异步实体对象集合信息</returns>
        public async Task<ResultList<T>> SelectModelItemsTask<T>(ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //异步查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = await this.ContextService.Set<T>().AsNoTracking().ToListAsync();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = await this.ContextService.Set<T>().ToListAsync();
                        break;
                }
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            //返回处理数据
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询]
        /// </summary>
        /// <param name="argWhereLambda">查询条件(lambda表达式的形式生成表达式目录树)</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public async Task<ResultList<T>> SelectModelItemsTask<T>(Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //查询方法，去除状态跟踪 AsNoTracking
                        ResultData.Data = await this.ContextService.Set<T>().Where(argWhereLambda).AsNoTracking().ToListAsync();
                        break;
                    case ExecuteStatus.Yes:
                        ResultData.Data = await this.ContextService.Set<T>().Where(argWhereLambda).ToListAsync();
                        break;
                }
                //返回处理数据
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[根据条件查询和名称排序]
        /// </summary>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argSortName">排序名称</param>
        /// <param name="argSortDirection">asc 或 desc</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是跟踪的</param>
        /// <returns></returns>
        public async Task<ResultList<T>> SelectModelItemsTask<T>(Expression<Func<T, bool>> argWhereLambda, string argSortName, string argSortDirection, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            return await Task.Run(() =>
            {
                return this.SelectModelItems(argWhereLambda, argSortName, argSortDirection, argTrackStatus);
            });
        }
        /// <summary>
        /// 查询数据[根据条件查询和Lambda排序]
        /// </summary>
        /// <typeparam name="Tkey">排序字段类型</typeparam>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argOrderLambda">排序条件</param>
        /// <param name="argSortStatus">排序状态【Yes升序,No降序/倒序】</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是跟踪的</param>
        /// <returns></returns>
        public async Task<ResultList<T>> SelectModelItemsTask<T, Tkey>(Expression<Func<T, bool>> argWhereLambda, Expression<Func<T, Tkey>> argOrderLambda, ExecuteStatus argSortStatus = ExecuteStatus.Yes, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            return await Task.Run(() =>
            {
                return this.SelectModelItems(argWhereLambda, argOrderLambda, argSortStatus, argTrackStatus);
            });
        }
        /// <summary>
        /// 查询分页数据[根据条件查询和Lambda排序]
        /// </summary>
        /// <typeparam name="Tkey">排序字段类型</typeparam>
        /// <param name="argPageIndex">页码</param>
        /// <param name="argPageSize">页容量/每页数量</param>
        /// <param name="argWhereLambda">查询条件</param>
        /// <param name="argOrderLambda">排序条件</param>
        /// <param name="argSortStatus">排序状态【Yes升序,No降序/倒序】</param>
        ///  <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <returns></returns>
        public async Task<ResultListPage<T>> SelectModelItemsPagerTask<T, Tkey>(int argPageIndex, int argPageSize, Expression<Func<T, bool>> argWhereLambda, Expression<Func<T, Tkey>> argOrderLambda, ExecuteStatus argSortStatus = ExecuteStatus.Yes, ExecuteStatus argTrackStatus = ExecuteStatus.No) where T : class
        {
            return await Task.Run(() =>
            {
                return this.SelectModelItemsPager(argPageIndex, argPageSize, argWhereLambda, argOrderLambda, argSortStatus, argTrackStatus);
            });
        }

        /// <summary>
        /// 查询数据[执行SQL语句操作]
        /// 注：查询必须返回实体的所有属性字段；结果集中列名必须与属性映射的项目匹配；查询中不能包含关联数据
        /// 除Select以外其他的SQL语句无法执行
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public ResultList<T> SelectExecuteSQL<T>(string argSQLText, ExecuteStatus argTrackStatus = ExecuteStatus.No, params DbParameter[] argCommandParms) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //表示不跟踪状态，默认不跟踪
                        ResultData.Data = this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).AsNoTracking().ToList();
                        break;
                    case ExecuteStatus.Yes: //表示跟踪状态
                        ResultData.Data = this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).ToList();
                        break;
                }
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL语句查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "执行SQL语句查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[执行SQL语句操作]
        /// 注：查询必须返回实体的所有属性字段；结果集中列名必须与属性映射的项目匹配；查询中不能包含关联数据
        /// 除Select以外其他的SQL语句无法执行
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argWhereLambda">执行的T-SQL命令：查询Lambda条件</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public ResultList<T> SelectExecuteSQL<T>(string argSQLText, Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No, params DbParameter[] argCommandParms) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //表示不跟踪状态，默认不跟踪
                        ResultData.Data = this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).Where(argWhereLambda).AsNoTracking().ToList();
                        break;
                    case ExecuteStatus.Yes: //表示跟踪状态
                        ResultData.Data = this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).Where(argWhereLambda).ToList();
                        break;
                }
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL语句查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "执行SQL语句查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[执行SQL语句操作]
        /// 注：查询必须返回实体的所有属性字段；结果集中列名必须与属性映射的项目匹配；查询中不能包含关联数据
        /// 除Select以外其他的SQL语句无法执行
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public async Task<ResultList<T>> SelectExecuteSQLTask<T>(string argSQLText, ExecuteStatus argTrackStatus = ExecuteStatus.No, params DbParameter[] argCommandParms) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //表示不跟踪状态，默认不跟踪
                        ResultData.Data = await this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).AsNoTracking().ToListAsync();
                        break;
                    case ExecuteStatus.Yes: //表示跟踪状态
                        ResultData.Data = await this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).ToListAsync();
                        break;
                }
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL语句查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "执行SQL语句查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
        /// <summary>
        /// 查询数据[执行SQL语句操作]
        /// 注：查询必须返回实体的所有属性字段；结果集中列名必须与属性映射的项目匹配；查询中不能包含关联数据
        /// 除Select以外其他的SQL语句无法执行
        /// </summary>
        /// <typeparam name="T">对象模型</typeparam>
        /// <param name="argSQLText">执行的T-SQL命令：SQL语句 或 存储过程名称</param>
        /// <param name="argWhereLambda">执行的T-SQL命令：查询Lambda条件</param>
        /// <param name="argTrackStatus">是否跟踪状态，默认是不跟踪的</param>
        /// <param name="argCommandParms">行的T-SQL命令参数：可变参数数组</param>
        /// <returns></returns>
        public async Task<ResultList<T>> SelectExecuteSQLTask<T>(string argSQLText, Expression<Func<T, bool>> argWhereLambda, ExecuteStatus argTrackStatus = ExecuteStatus.No, params DbParameter[] argCommandParms) where T : class
        {
            ResultList<T> ResultData = new ResultList<T>();
            try
            {
                switch (argTrackStatus)
                {
                    default:
                    case ExecuteStatus.No:  //表示不跟踪状态，默认不跟踪
                        ResultData.Data = await this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).Where(argWhereLambda).AsNoTracking().ToListAsync();
                        break;
                    case ExecuteStatus.Yes: //表示跟踪状态
                        ResultData.Data = await this.ContextService.Set<T>().FromSqlRaw(argSQLText, argCommandParms).Where(argWhereLambda).ToListAsync();
                        break;
                }
                if (ResultData.Data == null || ResultData.Data.Count <= 0)
                {
                    ResultData.ResultCode = ResultStatus.Failure;
                    ResultData.ResultMsg = "执行SQL语句查询数据失败";
                }
            }
            catch (Exception ep)
            {
                ResultData.ResultCode = ResultStatus.Exception;
                ResultData.ResultMsg = "执行SQL语句查询数据异常：" + (ep.InnerException != null ? ep.InnerException.Message : ep.Message);
            }
            return ResultData;
        }
    }
}
